package com.xmmxjy.pay.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xmmxjy.common.util.ContextHolderUtils;
import com.xmmxjy.common.util.HttpClientUtil;
import com.xmmxjy.common.util.Tools;
import com.xmmxjy.pay.entity.APIResult;
import com.xmmxjy.pay.entity.CreditOrderEntity;
import com.xmmxjy.pay.service.CreditOrderService;
import javassist.bytecode.stackmap.BasicBlock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xmmxjy
 * 支付接口
 */
@Controller
@RequestMapping("/pay")
public class PayController {
    //支付平台url
    private static String pay_url = "http://192.168.1.196:9080/blue-app-web/pay/main";
    //支付平台appId
    private static String blueAppId = "dwtt";

    //订单状态 未支付
    private static String ORDER_STATUS_0 = "0";

    //订单状态 支付完成
    private static String ORDER_STATUS_1 = "1";

    //订单状态 其他
    private static String ORDER_STATUS_2 = "2";

    private static Logger log = LoggerFactory.getLogger(PayController.class);
    @Autowired
    private CreditOrderService orderService;

    @RequestMapping("/unifiedorder")
    @ResponseBody
    public Object unifiedOrder(HttpServletRequest request, HttpServletResponse response) {
        //返回给app的参数
        APIResult result = new APIResult();
        //请求支付平台参数map
        Map<String,String> requestMap = new HashMap<String,String>();
        //订单实体
        CreditOrderEntity creditOrderEntity = new CreditOrderEntity();

        //支付类型
        String payType = (String) request.getParameter("payType");
        log.info("payType : {}",payType);
        if (Tools.isEmpty(payType)) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }
        //支付系统
        String payOS = (String) request.getParameter("payOS");
        log.info("payOS : {}",payOS);
        if (Tools.isEmpty(payOS)) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }
        //积分数量
        String creditNumStr = (String) request.getParameter("creditNum");
        log.info("creditNum : {}",creditNumStr);
        if (Tools.isEmpty(creditNumStr)) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }
        int creditNum = 0;
        try {
            creditNum = Integer.parseInt(creditNumStr);
        } catch (Exception e) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }

        //商品名称 非必输
        String body = (String) request.getParameter("body");
        log.info("body : {}",body);
        if (Tools.isEmpty(body)) {
            body = "积分充值";
        }
        //商品详情
        String detail = (String) request.getParameter("detail");
        log.info("detail : {}",detail);
        //订单编号
        /*String outTradeNo = (String)request.getParameter("outTradeNo");
        log.info("outTradeNo : {}",outTradeNo);
        if (Tools.isEmpty(outTradeNo)) {
            result.setResult("false");
            result.setMessage("400");
            return request;
        }*/
        String appUserId = (String) request.getParameter("appuserId");
        log.info("appuserId : {}",appUserId);
        int appuserId = Integer.parseInt(appUserId);
        String totalFee = (String) request.getParameter("totalFee");
        log.info("totalFee : {}",totalFee);
        if (Tools.isEmpty(totalFee)) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }
        double total = 0D;
        try {
            total = Double.parseDouble(totalFee);
        } catch (Exception e) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }
        //用户ID
        String spbillCreateIp = Tools.getRemoteHost(request);
        log.info("spbillCreateIp : {}",spbillCreateIp);
        //商品标记，代金券或立减优惠功能的参数，非必输
        String goodTag = request.getParameter("goodTag");
        log.info("goodTag : {}",goodTag);
        //指定支付方式 ，非必输，no_credit--指定不能使用信用卡支付
        String limitPay = request.getParameter("limitPay");
        log.info("limitPay : {}",limitPay);

        creditOrderEntity.setAppuserId(appuserId);
        creditOrderEntity.setCreditNum(creditNum);
        creditOrderEntity.setMoney(total);
        creditOrderEntity.setOrderTime(new Date());
        creditOrderEntity.setPayOs(payOS);
        creditOrderEntity.setOrderStatus(ORDER_STATUS_0);
        creditOrderEntity.setSubject(body);
        creditOrderEntity.setSubjectDetail(detail);
        Long orderId = orderService.saveOrder(creditOrderEntity);
        if (orderId == null) {
            result.setResult("false");
            result.setMessage("500");
            return result;
        }
        requestMap.put("blueAppId",blueAppId);
        requestMap.put("payType",payType);
        requestMap.put("body",body);
        requestMap.put("detail",detail);
        requestMap.put("outTradeNo",orderId + "");
        requestMap.put("totalFee",totalFee);
        requestMap.put("spbillCreateIp",spbillCreateIp);
        requestMap.put("goods_tag",goodTag);
        requestMap.put("limit_pay",limitPay);
        String obj = HttpClientUtil.getInstance().sendHttpPost(pay_url,requestMap);
        log.info("obj : " + obj);
        JSONObject json = JSONObject.parseObject(obj);
        log.info("json : " + json);
        if (payType.equals("weixin")) {
            String arraystr = (String) json.get("obj");
            JSONArray array = JSONObject.parseArray(arraystr);
            JSONObject jo = (JSONObject) array.get(0);

/*        String appid = (String)jo.get("appid");
        String sign = (String)jo.get("sign");
        String partnerid = (String)jo.get("partnerid");

        log.info("appid : " + appid);*/
            result.setInfo(jo);
        } else {
            String sign = (String)json.get("obj");
            log.info("sign : " + sign);
            result.setInfo(sign);
        }
        result.setMessage("200");
        result.setResult("true");

        return result;
    }

    @RequestMapping("/orders")
    @ResponseBody
    public Object orderListByUserId(Integer appuserId,HttpServletRequest request,HttpServletResponse response) {
        APIResult result = new APIResult();
        if (appuserId == null) {
            result.setResult("false");
            result.setMessage("400");
            return result;
        }
        result.setResult("true");
        result.setMessage("200");
        List<CreditOrderEntity> creditOrderEntityList = orderService.selectByUserId(appuserId);
        if (Tools.isListEmpty(creditOrderEntityList)) {
            return result;
        }
        result.setInfo(creditOrderEntityList);
        return result;
    }
    @RequestMapping("/notice")
    @ResponseBody
    public String notice(Long orderId,String payType,String tradeStatus,String tradeNo,HttpServletRequest request,HttpServletResponse response){
        if (orderId == null) {
            return "fail";
        }
        CreditOrderEntity order =  orderService.selectByPrimaryKey(orderId);
        if (order == null) {
            return "fail";
        }
        if (tradeStatus.equals("success")) {
            order.setPayTime(new Date());
            order.setOrderStatus(ORDER_STATUS_1);
            return "success";
        } else {
            order.setOrderStatus(ORDER_STATUS_0);
        }
        return "fail";
    }
}
